<template>
  <div>
    <main-layout>
      <div class="list-container">
        <auth-tag code="13006|13007|13008" tips="无权访问">
          <vTable   ref="vGridTable"
                class="order-list-postion"
                :columnsList="columnsList"
                addCode="13009"
                addText="添加采购单"
                apiUrl="/boss/oms-order/oms-order-list"
                :pageSize="15"
                :formConfig="formConfig"
                :toolbarConfig="false"
                :showOverflow="false"
                :recombinationData="true"
                :rowClassName="rowClassName"
                @saveClick="openAdd"
                :spanList="['orderSn']"
                :queryData="{createId:userStore.userInfo.userId}">
                <template #cells="{row}">
                    <div class="cells-view">
                        <div class="image-view"> 
                          <template v-if="row.pmsSpuImagesVoList && row.pmsSpuImagesVoList.length>0">
                            <imageView  :url="row.pmsSpuImagesVoList[0].url" :list="row.pmsSpuImagesVoList.map((item)=>item.url)" />
                          </template>
                        </div>
                        <div>   
                            <router-link style="color: #409EFF;" :to="`./spu-detail?Id=${row.skuInfoId}&spuId=${row.spuInfoId}`">
                                  {{ row.spuName }}
                            </router-link>
                          <div>
                            <el-tag  type="success" style="margin-top:10px;margin-right:10px" v-for="item in row.spuService?.split(',')">{{item}}</el-tag>
                          </div>
                        </div>
                    </div>
                  </template>
                  <template #cells1="{row}">
                    <span style="color:#333;font-size:13px;">￥</span>
                     <span style="color:#333;font-size:16px;font-weight: bold;">{{(row.subtotalExecAmount?.amount+row.subtotalYunfeiAmount?.amount).toFixed(2) }}</span>
                     <div v-if="row.subtotalYunfeiAmount?.amount">
                      (含运费:<span style="color:#333;font-size:13px;">￥</span>  
                      <span style="color:#333;font-size:13px;font-weight: bold;">{{row.subtotalYunfeiAmount.standardString }}</span>)
                     </div>
                  </template>
                  <template #actions="{row}">
                      <auth-tag code="">
                        <div class="order-nocss">
                           <div>订单号:{{row.orderSn||'--'}}</div>
                           <div>创建人:{{row.createName||'--'}} <span style="padding-left:100px;padding-right:30px">创建日期:{{row.createTime||'--'}}</span></div>
                        </div>
                        <!-- 订单状态[1->待付款；2->待发货；3->已发货；4->已完成；4->已关闭；5->无效订单]	-->
                        <!-- <template v-if="row.status==1">
                          <vxe-button size="mini" status="primary" @click="btnPay(row)" icon="vxe-icon-send">付款</vxe-button>
                          <div style="padding-top:10px;">
                            <vxe-button type="text" @click="btnClose(row)" status="danger" icon="vxe-icon-error-circle" content="关闭交易"></vxe-button>
                            <vxe-button type="text" @click="btnGo(row)" status="primary" icon="vxe-icon-copy" content="订单详情"></vxe-button>
                          </div>
                        </template>
                        <template v-else-if="row.status==4">
                          <vxe-button size="mini" status="primary" @click="btnApply(row)" icon="vxe-icon-send">售后申请</vxe-button>
                          <div style="padding-top:10px;">
                            <vxe-button type="text" @click="btnGo(row)" status="primary" icon="vxe-icon-copy" content="订单详情"></vxe-button>
                          </div>
                        </template>
                        <template v-else>
                          <vxe-button size="mini" status="primary" @click="btnGo(row)" icon="vxe-icon-copy">订单详情</vxe-button>
                        </template> -->
                        <vxe-button size="mini" status="primary" @click="btnGo(row)" icon="vxe-icon-copy">订单详情</vxe-button>

                          <!-- <vxe-button size="mini" status="primary" @click="btnSend(row)" icon="vxe-icon-merge-cells">寄回货物</vxe-button>
                          <div style="padding-top:10px;">
                            <vxe-button type="text" @click="btnGo(row)" status="primary" icon="vxe-icon-copy" content="订单详情"></vxe-button>
                          </div> -->
                      </auth-tag>
                  </template>
            </vTable>
        </auth-tag>
      </div>
    </main-layout>
    <sendView v-if="addFlag" :show="addFlag" :editData="editData" @success="refreshTable" @close="addFlag=false" />

  </div>
</template>

<script setup name="purchase-list">
import { nextTick, ref,computed,onMounted } from 'vue'
import { useRouter } from 'vue-router'
import mainLayout from '@/components/custom/mainLayout.vue'
import imageView from '@/components/custom/image.vue'
import { useUserStore } from '@/pinia/modules/user'
import { closeOrder } from '@/api/order'
import sendView from './components/send.vue'
import { VXETable } from 'vxe-table'
const router = useRouter()
const userStore = useUserStore()
onMounted(() => {
})

const vGridTable = ref(null)
const addFlag = ref(false)
const editData = ref({})
const statusList =ref([
  {label:'待付款',value:0},
  {label:'待发货',value:1},
  {label:'已发货',value:2},
  {label:'已完成',value:3},
  {label:'已关闭',value:4},
  {label:'无效订单',value:5}
])

const  formConfig = computed(
    ()=>{
    return {
        titleWidth: 100,
        titleAlign: 'center',
        items: [
         {
            field: 'orderSn',
            title: '订单号',
            span: 5,
            itemRender: {name: '$input', props: {placeholder: '订单号', clearable: true}}
          },
          {
            field: 'spuName',
            title: '商品名称',
            span: 5,
            itemRender: {name: '$input', props: {placeholder: '商品名称', clearable: true}}
          },
          {
            field: 'receiverName',
            title: '收货人',
            span: 5,
            itemRender: {name: '$input', props: {placeholder: '收货人', clearable: true}}
          },
          {
            field: 'receiverPhone',
            title: '收货人电话',
            span: 5,
            itemRender: {name: '$input', props: {placeholder: '收货人电话', clearable: true}}
          },
          {
            field: 'status',
            title: '状态',
            span: 5,
            itemRender: {name: '$select', 
            props: {placeholder: '全部', clearable: true},
            options:statusList
          }
          },
          {
            field: 'dateRange',
            title: '创建日期',
            span: 5,
            itemRender: {},
            slots: { default: 'dateRange' }
          },
          {
            field: '',
            title: '',
            span: 5,
            className:'from-right-btn-add',
            showTitle:false,
            slots: { default: 'addButtom' }
          },
          {
            align: 'center', collapseNode: false,
            itemRender: {
              name: '$buttons',
              children: [
                {props: {type: 'submit', icon: 'vxe-icon-search', content: '查询', status: 'primary'}},
                {props: {type: 'reset', icon: 'vxe-icon-refresh', content: '重置'}}
              ]
            }
          }
        ]
    }
})


const columnsList = ref([
      {field: 'roleName', title: '货品',minWidth:'200',align:'left', slots: {default: 'cells'}},
      {field: 'salesAmount.standardString', title: '单价(元)',minWidth:'80',align:'center'},
      {field: 'buyQuantity',minWidth:'80', title: '数量',align:'center'},
      {field: 'subtotalExecAmount.standardString', title: '总金额(元)',minWidth:'80',align:'center', slots: {default: 'cells1'}},
      {field: 'statusMeaning', title: '订单状态',minWidth:'110',align:'center'},
      {title: '操作', width: 200,fixed:'right',field: 'orderSn',align:'center', slots: {default: 'actions'}}
   ])


const rowClassName =({row})=>{
  let tableData =Array.from(new Set(vGridTable.value.getTableData().map((item)=>item.orderSn))) 
  let newlist =[]
  tableData.forEach((item) => {
    newlist.push({
      orderSn:item,
      list:vGridTable.value.getTableData().filter((dt)=>{
        return dt.orderSn == item
      }).map((item,index)=>{
        item.indexNo = index
        return item 
      })
    })
  })
  let lastList =[]
  newlist.forEach((item)=>{
    item.list.forEach((dt)=>{
      lastList.push(dt)
    })
  })
 
  if(lastList.find((item)=>item.orderItemId==row.orderItemId).indexNo==0){
    return 'row-padding-top'
  }else{
    return null
  }
}
const refreshTable = () => {
  vGridTable.value.loadData()
}
const openAdd = () => {
  router.push(`./purchase-order`)
}
const btnPay = (row) => {
  router.push(`./pay-order`)
}
const btnApply = (row) => {
  router.push(`./apply-service`)
}

const btnClose = async(row) => {
  const type = await VXETable.modal.confirm('您确定要关闭该订单吗？')
 if(type=='confirm'){
   let res= await closeOrder([row.orderId])
   if(res.success){
    VXETable.modal.message({ content: '关闭成功' })
    refreshTable()
   }else{
    VXETable.modal.message({ content: res.message })
   }
 }}

const btnGo = async(item) => {
  router.push(`./order-detail?orderId=${item.orderId}`)
}

const btnSend = (row)=>{
  addFlag.value = true
}
</script>

<style lang="scss" scoped>
.cells-view {
 display: flex;
 justify-content: flex-start;
 .image-view{
    width:60px;
    height:60px;
    background-color: #f7f7f7;
    margin-right:6px;
    flex-shrink: 0;
 }
}
.order-nocss{
    position: absolute;
    z-index: 1;
    width: 98.5%;
    height: 35px;
    top: 0;
    left: 0;
    background-color: #fff;
    line-height: 35px;
    font-size: 14px;
    padding: 0 10px;
    border: 1px solid #e8eaec;
    border-top: none;
    color: #606266;
    font-weight: bold;
    border-right: none;
    display: flex;
    justify-content: space-between;
    background-color: var(--vxe-table-header-background-color);
}

</style>